package com.tanhua.server.service;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.common.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

/**
 * 用户业务层
 * 这里用来调用SSO校验token接口
 */
@Service
@Slf4j
public class UserService {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${tanhua.sso.url}")
    private String ssoUrl;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 校验token
     * 调用SSO接口实现
     *
     * @param token 用户令牌
     * @return
     */
    public User queryUserByToken(String token) {
        // 拼接请求参数
        String url = ssoUrl + "/user/" + token;

        try {
            // 发起请求，货期返回值
            String result = restTemplate.getForObject(url, String.class);

            if (StrUtil.isEmpty(result)) {
                return null;
            }

            User user = MAPPER.readValue(result, User.class);

            if (user != null) {
                return user;
            }

        } catch (IOException e) {
            log.error("userService校验用户令牌错误 token = " + token, e);
        }
        return null;
    }
}
